// parentId上移
export const filterWithParentId = (
    allList: IListItem[],
    selectedIds: string[],
    rootParentId?: string,
) => {
    const idMap: Record<string, IListItem> = {}
    const selectedIdMap: Record<string, boolean> = selectedIds.reduce(
        (acc, id) => {
            acc[id] = true
            return acc
        },
        {} as Record<string, boolean>,
    )
    const selectedList = allList.filter((item) => {
        // filter的同时建立idMap
        idMap[item.id] = item
        return selectedIds.includes(item.id)
    })
    // 设置parentId，如果某一项的parentId不在选择的列表中，则往上移动
    selectedList.forEach((item) => {
        // parentId为空，则不处理
        if (!item.parentId) {
            item.parentId = rootParentId
            return
        }
        // parentId在选择的列表中，则不处理
        if (selectedIdMap[item.parentId]) {
            return
        }
        // 往上移动
        let newParentId: string | undefined = item.parentId
        while (newParentId && !selectedIdMap[newParentId]) {
            newParentId = idMap[newParentId]?.parentId
        }
        item.parentId = newParentId || rootParentId
    })
    return selectedList
}
